package edu.zut.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "SessionDemo", value = "/session/demo1")
public class SessionDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //session的创建,如果服务器中保存的有对应session，就用，如果没有，就新建
        HttpSession session = request.getSession();
//        request.getSession(true);
//        request.getSession(false);
        if (session.isNew()) {
            System.out.println("当前session是新建的");
        }else
            System.out.println("这是旧的session");
        //id
        String id = session.getId();
        Cookie cookie = new Cookie("JSESSIONID", id);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        //想浏览器关闭，用户再次打开浏览器访问时候依然能找到对应的session
        cookie.setMaxAge(60*60);
        //session默认30分钟失效
        session.setMaxInactiveInterval(60*60);
        //保存数据
        session.setAttribute("myName","xueyin");
        session.setAttribute("myAge",21);
        //获取数据
        Object myName = session.getAttribute("myName");
        System.out.println("myName = " + myName);
        response.addCookie(cookie);
        response.getWriter().write(id);


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
